﻿using System;
using System.Collections;
using System.Data;
using System.Text;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using PAS.Helper;

namespace PAS.UserControls
{
    public partial class UcSimpleDataList : UserControl
    {
        public string InnerSql
        {
            get
            {
                object obj = SessionHelper.GetSession(this, "InnerSql");
                return obj == null ? "" : obj.ToString();
            }
            set { SessionHelper.SetSession(this, "InnerSql", value); }
        }

        public string KeyColumnName
        {
            get
            {
                object obj = SessionHelper.GetSession(this, "KeyColumnName");
                return obj == null ? "" : obj.ToString();
            }
            set { SessionHelper.SetSession(this, "KeyColumnName", value); }
        }

        public string DbTableName
        {
            get
            {
                object obj = SessionHelper.GetSession(this, "DbTableName");
                return obj == null ? "" : obj.ToString();
            }
            set { SessionHelper.SetSession(this, "DbTableName", value); }
        }

        public string SortExpress
        {
            get
            {
                object obj = SessionHelper.GetSession(this, "SortExpress");
                return obj == null ? "" : obj.ToString();
            }
            set { SessionHelper.SetSession(this, "SortExpress", value); }
        }

        public int PageSize
        {
            get
            {
                object obj = ViewState[ClientID + "PageSize"];
                return obj == null ? 0 : Convert.ToInt32(obj);
            }
            set { ViewState[ClientID + "PageSize"] = value; }
        }

        public int CurrPageIndex
        {
            get
            {
                object obj = ViewState[ClientID+"CurrPageIndex"];
                return obj == null ? 0 : Convert.ToInt32(obj);
            }
            set { ViewState[ClientID + "CurrPageIndex"]=value; }
        }

        public int Width
        {
            get
            {
                object obj = ViewState[ClientID + "Width"];
                return obj == null ? 0 : Convert.ToInt32(obj);
            }
            set { ViewState[ClientID + "Width"] = value; }
        }

        public string QueryCondition
        {
            get
            {
                object obj = SessionHelper.GetSession(this, "QueryCondition");
                return obj == null ? "" : obj.ToString();
            }
            set { SessionHelper.SetSession(this, "QueryCondition", value); }
        }


        public string[] ColumnNames
        {
            get
            {
                object obj = SessionHelper.GetSession(this, "ColumnNames");
                if (obj != null && obj is string[]) return ((string[])obj);
                return null;
            }
            set { SessionHelper.SetSession(this, "ColumnNames", value); }
        }

        public string[] ColumnTypes
        {
            get
            {
                object obj = SessionHelper.GetSession(this, "ColumnTypes");
                if (obj != null && obj is string[]) return ((string[]) obj);
                return null;
            }
            set { SessionHelper.SetSession(this, "ColumnTypes", value); }
        }

        public string[] ColumnWidths
        {
            get
            {
                object obj = SessionHelper.GetSession(this, "ColumnWidths");
                if (obj != null && obj is string[]) return ((string[]) obj);
                return null;
            }
            set { SessionHelper.SetSession(this, "ColumnWidths", value); }
        }

        public string[] ColumnMemos
        {
            get
            {
                object obj = SessionHelper.GetSession(this, "ColumnMemos");
                if (obj != null && obj is string[]) return ((string[]) obj);
                return null;
            }
            set { SessionHelper.SetSession(this, "ColumnMemos", value); }
        }

        protected override void OnInit(EventArgs e)
        {
            base.OnInit(e);
            tblFooter.Visible = (!string.IsNullOrEmpty(InnerSql));
            if (tblFooter.Visible)
                BindData();
            
        }

        protected void Page_Load(object sender, EventArgs e)
        {
        }

        public void BindData()
        {
            var dbHlp = new DataConnHelper();
            var sql = InnerSql;
            if (string.IsNullOrEmpty(SortExpress))
                sql += " Select * from ( "+InnerSql+" ) k Order by " + SortExpress;
            var dt = dbHlp.GetDataTable(sql);
            tblData.Rows.Clear();
            Width = 0;
            CreateList(dt);
        }

        private void CreateList(DataTable dt)
        {
            if (dt != null && dt.Columns.Count > 0)
            {
                tblFooter.Visible = true;
                tblData.Attributes["class"] = "SimpleDataList";
                CreateListHeader(dt.Columns, tblData);
                var drc = new ArrayList();
                lblCurrPageIndex.Text = (CurrPageIndex+1).ToString();
                var pageAmount = Math.Ceiling(dt.Rows.Count*1.0/PageSize);
                btnLastPage.Enabled = btnNextPage.Enabled = (CurrPageIndex + 1 != pageAmount);
                btnFirstPage.Enabled = btnPevPage.Enabled = CurrPageIndex != 0;
                lblPageSize.Text = PageSize.ToString();
                lblRowAmount.Text = dt.Rows.Count.ToString();
                lblTotalPageAmount.Text = pageAmount.ToString();
                if(PageSize > 0)
                {
                    for (var i = CurrPageIndex * PageSize; i <= (CurrPageIndex + 1) * PageSize && i < dt.Rows.Count; i++)
                        drc.Add(dt.Rows[i]);
                }
                else
                {
                    for (var i = 0; i < dt.Rows.Count; i++)
                        drc.Add(dt.Rows[i]);
                }
                CreateListData(drc, tblData);
            }
        }

        private void CreateListHeader(DataColumnCollection dcc, HtmlTable tbl)
        {
            var tr = new HtmlTableRow();
            tr.Attributes["class"] = "SimpleDataListHeader";
            tbl.Controls.Add(tr);
            int colIndex = 0;
            ColumnNames = new string[dcc.Count];
            foreach (DataColumn dc in dcc)
            {
                ColumnNames[colIndex] = dc.ColumnName;
                var th = new HtmlTableCell();
                tr.Controls.Add(th);
                string colType = ColumnTypes[colIndex];
                if (colType == "hidden")
                    th.Style["display"] = "none";
                th.InnerText = string.IsNullOrEmpty(ColumnMemos[colIndex]) ? dc.ColumnName : ColumnMemos[colIndex];
                string colWidth = ColumnWidths[colIndex];
                if (!string.IsNullOrEmpty(colWidth))
                {
                    var iWidth =
                        Convert.ToInt32(colWidth.EndsWith("px") ? colWidth.Substring(0, colWidth.Length - 3) : colWidth);
                    th.Width = iWidth+"px";
                    Width += iWidth;
                }
                colIndex++;
            }
            tr.Controls.Add(new HtmlTableCell {InnerText = "操作", Width="96px"});
            Width += 104;
            if (Width < 400) Width = 400;
            tblFooter.Style["width"] = tbl.Style["width"] = Width + "px";
        }

        private void CreateListData(ArrayList drc, HtmlTable tbl)
        {
            int pageRowAmount = 0;
            foreach (DataRow dr in drc)
            {
                var tr = new HtmlTableRow();
                tbl.Controls.Add(tr);
                pageRowAmount++;
                tr.Attributes["class"] = pageRowAmount%2 == 0 ? "SimpleDataListRowAl" : "SimpleDataListRow";

                int colIndex = 0;
                foreach (DataColumn dc in dr.Table.Columns)
                {
                    var td = new HtmlTableCell();
                    tr.Controls.Add(td);
                    string cellVal = Convert.ToString(dr[dc.ColumnName]);
                    string colType = ColumnTypes[colIndex];
                    if (colType == "hidden")
                        td.Style["display"] = "none";
                    if (colType == "text")
                    {
                        var txt = new TextBox {Text = cellVal, ID = pageRowAmount + "_txt" + dc.ColumnName};
                        string colWidth = ColumnWidths[colIndex];
                        if (!string.IsNullOrEmpty(colWidth))
                            txt.Width = Unit.Pixel(Convert.ToInt32(colWidth) - 8);
                        td.Controls.Add(txt);
                    }
                    else
                        td.InnerText = cellVal;
                    colIndex++;
                }

                var tdOp = new HtmlTableCell();
                tr.Controls.Add(tdOp);
                var btnEdit = new Button
                                  {
                                      Text = "修改",
                                      OnClientClick = "return InitCheckInfo(this.id);",
                                      ID = pageRowAmount + "_btnEdit"
                                  };
                
                tdOp.Controls.Add(btnEdit);tdOp.Controls.Add(new HtmlGenericControl{InnerText = "  "});
                btnEdit.Click += btnEdit_Click;
                var btnDelete = new Button {Text = "删除", ID = pageRowAmount + "_btnDelete", OnClientClick="return confirm('确定删除记录');"};
                tdOp.Controls.Add(btnDelete);
                btnDelete.Click += btnDelete_Click;
            }
        }

        private void btnDelete_Click(object sender, EventArgs e)
        {
            if (sender is Button && ((Button)sender).Parent is HtmlTableCell &&
                ((Button)sender).Parent.Parent is HtmlTableRow)
            {
                var row = ((HtmlTableRow)((Button)sender).Parent.Parent);
                string strKeyColVal = "";
                for (int i = 0; i < ColumnNames.Length; i++)
                {
                    string colName = ColumnNames[i];
                    HtmlTableCell cell = row.Cells[i];
                    string colValue = "";
                    if (cell.Controls.Count > 0 && cell.Controls[0] is TextBox)
                        colValue = ((TextBox)cell.Controls[0]).Text;
                    else
                        colValue = cell.InnerText;
                    if (colName == KeyColumnName)
                        strKeyColVal = colValue;
                }
                string sql = "Delete From" + " [" + DbTableName + "] Where [" + KeyColumnName + "]=" +
                             strKeyColVal + "";
                int reVal = new DataConnHelper().ExecSqlCommand(sql);
                if (reVal > 0)
                    Alert.MessageBox("删除成功");
                BindData();
            }
        }

        protected void btnEdit_Click(object sender, EventArgs e)
        {
            if (sender is Button && ((Button) sender).Parent is HtmlTableCell &&
                ((Button) sender).Parent.Parent is HtmlTableRow)
            {
                var row = ((HtmlTableRow) ((Button) sender).Parent.Parent);
                var sbUpdateColWord = new StringBuilder();
                string strKeyColVal = "";
                for (int i = 0; i < ColumnNames.Length; i++)
                {
                    string colName = ColumnNames[i];
                    HtmlTableCell cell = row.Cells[i];
                    string colValue = "";
                    if (cell.Controls.Count > 0 && cell.Controls[0] is TextBox)
                        colValue = ((TextBox) cell.Controls[0]).Text;
                    else
                        colValue = cell.InnerText;
                    if (colName == KeyColumnName)
                        strKeyColVal = colValue;
                    else
                    {
                        if (sbUpdateColWord.Length > 0) sbUpdateColWord.Append(",");
                        sbUpdateColWord.Append("[" + colName + "]='" + colValue + "'");
                    }
                }
                string sql = "Update [" + DbTableName + "] Set " + sbUpdateColWord + "  Where [" + KeyColumnName + "]=" +
                             strKeyColVal + "";
                int reVal = new DataConnHelper().ExecSqlCommand(sql);
                if (reVal > 0)
                    Alert.MessageBox("修改成功");
                BindData();
            }
        }

        protected void btnFirstPage_Click(object sender, EventArgs e)
        {
            CurrPageIndex = 0;
            BindData();
        }

        protected void btnPevPage_Click(object sender, EventArgs e)
        {
            CurrPageIndex--;
            BindData();
        }

        protected void btnNextPage_Click(object sender, EventArgs e)
        {
            CurrPageIndex++;
            BindData();
        }

        protected void btnLastPage_Click(object sender, EventArgs e)
        {
            CurrPageIndex = Convert.ToInt32(lblTotalPageAmount.Text) - 1;
            BindData();
        }



    }
}